package com.lagou.factory;

import com.lagou.utils.TransactionManager;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * desc: 动态代理类
 *
 * @author tengfei wang
 * @version 1.0
 * @date Created in 7/9/2020
 */
public class DynamicProxy implements AopProxy {

    @Override
    public Object createProxy(Object o) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), (proxy, method, args) -> {
            Object invoke = method.invoke(o, args);
            return invoke;
        });
    }

    @Override
    public Object createProxyWithTransaction(Object o, List<Method> methods) {
        return Proxy.newProxyInstance(o.getClass().getClassLoader(), o.getClass().getInterfaces(), (proxy, method, args) -> {
            Object invoke = null;
            boolean anyMatch = methods.stream().anyMatch(w -> w.getName().equals(method.getName()));
            if (anyMatch) {
                TransactionManager.getInstance().beginTransaction();
                try {
                    invoke = method.invoke(o, args);
                    TransactionManager.getInstance().commit();
                } catch (Exception e) {
                    TransactionManager.getInstance().rollback();
                    throw e;
                }
                return invoke;
            }
            invoke = method.invoke(o, args);
            return invoke;
        });
    }
}
